package demo.core.runtime.extension;

import java.util.*;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

import demo.core.runtime.platform.Platform;

public class Context {
	private BundleContext bundleContext;
	private ServiceRegistration serviceReg = null;

	private Set<Object> extensions = new LinkedHashSet<Object>();
	private Set<String> extendPoints = new LinkedHashSet<String>();

	public Context(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
	}

	public BundleContext getBundleContext() {
		return bundleContext;
	}

	public void registerExtension(ExtendPoint extendPoint, Object extension) {
		try {
			ExtendRegTable regTable = Platform.getPointRegTable();
			regTable.addExtension(bundleContext.getBundle(),extendPoint, extension);
			extensions.add(extension);
			serviceReg = bundleContext.registerService(extendPoint.getId(),
					extension, null);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void unregister() {
		if (serviceReg != null)
			serviceReg.unregister();
		try {
			ExtendRegTable regTable = Platform.getPointRegTable();
			regTable.removeExtensions(extensions);
			extensions.clear();
			regTable.removeExtendPoints(extendPoints);
			extendPoints.clear();
		} catch (RemoveException ex) {
			ex.printStackTrace();
		}
	}

	public void registerExtendPoint(String extendPoint) {

		ExtendRegTable regTable = Platform.getPointRegTable();
		regTable.addExtendPoint(bundleContext.getBundle(),extendPoint);
		extendPoints.add(extendPoint);
	}

	public ExtendPoint getExtendPoint(String extendPoint) {
		ExtendRegTable regTable = Platform.getPointRegTable();
		return regTable.getExtendPoint(extendPoint);
	}
}
